package cn.remex.wechat;

import cn.remex.RemexConstants;
import cn.remex.core.exception.ServiceCode;
import cn.remex.core.util.Assert;
import cn.remex.core.util.JsonHelper;
import cn.remex.core.util.Judgment;
import cn.remex.core.util.PropertyReader;
import cn.remex.db.Database;
import cn.remex.db.sql.WhereRuleOper;
import cn.remex.wechat.config.WeChatApp;
import cn.remex.wechat.config.WeChatAppExt;
import cn.remex.wechat.config.WeChatAppType;
import cn.remex.wechat.models.WeChatAppConfig;
import cn.remex.wechat.utils.WeChatException;
import cn.remex.wechat.utils.WeChatUtils.WeChatApi;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by guoqi on 2016/2/26.
 * <p>
 * Modified by LHY 2016-8-23
 */
public class WeChat {
	public static String LINUX_PATH = File.separator + "data" + File.separator + "default" + File.separator + "wxxml";
	public static String WIN_PATH = "D:" + File.separator + "data" + File.separator + "default" + File.separator + "wxxml";
	public static String certLocalPath; // HTTP证书在服务器中的路径，用来加载证书用
	public static String certPassword; // HTTP证书的密码，默认等于MCHID
	//微信的地址配置
	private static Map<String, String> WeChatApiUrlMap = PropertyReader.getPropertiesHashMap(WeChat.class, "/wechat.properties");
	private static Map<String, WeChatApp> weChatAppMap = new HashMap<>();
	private static Map<String, String> appid_agentidToAppName = new HashMap<>();
	private static WeChatApp defaultWeChatApp;

	//操作具体的weChatapp
	public static void createWeChatApp(WeChatAppConfig weChatAppConfig) {
		WeChatApp weChatApp = new WeChatApp(weChatAppConfig);

		if (weChatAppMap.size() == 0 || weChatApp.getConfig().isDefaultApp()) {
			defaultWeChatApp = weChatApp;//默认把第一个设置为全局默认的微信应用
		}
		weChatAppMap.put(weChatApp.key(), weChatApp);
		appid_agentidToAppName.put(weChatAppConfig.getAppid() + "-" + (Judgment.nullOrBlank(weChatAppConfig.getAgentid()) ? "0" : weChatAppConfig.getAgentid()), weChatApp.key());
	}
	public static WeChatApp getWeChatApp() {
		return getWeChatApp(null, null);
	}
	public static WeChatApp getWeChatApp(String weChatAppName) {
		WeChatApp curWeChatApp = weChatAppMap.get(weChatAppName);
		Assert.notNull(curWeChatApp, ServiceCode.WEIXIN_CONFIG_ERROR, "微信配置或Appid错误，无法获取微信应用实例：weChatAppName=" + weChatAppName);
		return curWeChatApp;
	}
	public static WeChatApp getWeChatApp(String appId, String agentId) {
		WeChatApp curWeChatApp;
		if(Judgment.nullOrBlank(appId)&&Judgment.nullOrBlank(agentId)){
			curWeChatApp = defaultWeChatApp;
		}else if(!Judgment.nullOrBlank(appId) && Judgment.nullOrBlank(agentId)){
			curWeChatApp = weChatAppMap.get(appid_agentidToAppName.get(appId+"-0"));
		}else if(!Judgment.nullOrBlank(appId) && !Judgment.nullOrBlank(agentId)){
			curWeChatApp = weChatAppMap.get(appid_agentidToAppName.get(appId+"-"+agentId));
		}else {
			throw new WeChatException(ServiceCode.WEIXIN_CONFIG_ERROR, "appid为null，agentid不为null时，无法获得WeChatApp");
		}
		Assert.notNull(curWeChatApp, ServiceCode.WEIXIN_CONFIG_ERROR, "微信配置或Appid错误，无法获取微信应用实例：appId=" + appId);
		return curWeChatApp;
	}
	public static WeChatAppExt getWeChatAppExt() {
		return new WeChatAppExt(defaultWeChatApp);
	}
	public static WeChatAppExt getWeChatAppExt(String appId, String agentId) {
		return new WeChatAppExt(getWeChatApp(appId,agentId));
	}
	public static Map<String, WeChatApp> getWeChatAppMap() {
		return weChatAppMap;
	}

	//微信App 配置管理
	public static WeChatAppConfig saveWeChatAppConfig(WeChatAppConfig config){
		Database.store(config)
				.execute().assertEffectOneRow(ServiceCode.FAIL, "更新微信配置错误");
		return config;
	}
	public static WeChatAppConfig delWeChatAppConfig(WeChatAppConfig config){
		Database.delete(WeChatAppConfig.class)
				.filterById(config.getId())
				.execute().assertEffectOneRow(ServiceCode.FAIL, "更新微信配置错误");
		return config;
	}
	public static List<WeChatAppConfig> weChatAppConfigs(){
		return Database.select(WeChatAppConfig.class)
				.execute().obtainObjects(WeChatAppConfig.class);
	}
	public static void initWeChat(){
		weChatAppMap.clear();
		appid_agentidToAppName.clear();
		for (WeChatAppConfig config : weChatAppConfigs()){
			RemexConstants.logger.info("初始化微信配置，appid={},config={}",config.getAppid(), JsonHelper.toJsonString(config));
			createWeChatApp(config);
		}

	}

	//api路径工具
	public static String getApiUrl(WeChatAppType type, WeChatApi key) {
		String url = WeChatApiUrlMap.get(type.toString() + "." + key);
		Assert.notNullAndEmpty(url, ServiceCode.WEIXIN_CONFIG_ERROR, "微信ApiUrl没有再wechat.properties文件中配置：" + type + "." + key);
		return url;
	}
}
